package com.example.smartcity.ui.person

import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.example.smartcity.R
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.FragmentPersonBinding
import com.example.smartcity.logic.net_work.Response
import com.example.smartcity.logic.net_work.Response.getLogin
import com.example.smartcity.logic.net_work.Response.getLoginAll
import com.example.smartcity.logic.utils.ManageActivity.getSharedPreferences
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.person.Adapter.PersonListItemRecyclerViewAdapter
import com.example.smartcity.ui.person.login.LoginActivity
import com.example.smartcity.ui.person.login.infoActivity
import com.example.smartcity.ui.person.model.ListItemRecyclerViewEntity
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 个人中心
 */
class PersonFragment : Fragment(){


    // 懒加载
    private val viewModel by lazy {
        ViewModelProvider(this)[PersonViewModel::class.java]
    }

    private val array = ArrayList<ListItemRecyclerViewEntity>()

    private lateinit var mBindIng: FragmentPersonBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBindIng = FragmentPersonBinding.inflate(layoutInflater, container, false)
        // 设置列表数据
        initListItem()

        // 点击登录
        register()

       return mBindIng.root
    }


    /**
     * 点击登录
     */
    private fun register() {
        // 获取监听的控件
        val tvTitle = mBindIng.personTvTitle
        val btn = mBindIng.button
        tvTitle.setOnClickListener {
            activity?.getSharedPreferences("token", Context.MODE_PRIVATE).apply {
                if(this?.getBoolean("user", false) == true){
                    startActivity(Intent(context, infoActivity::class.java))
                }else startActivity(Intent(context, LoginActivity::class.java))
            }
        }

        btn.setOnClickListener {
            activity?.getSharedPreferences("token", Context.MODE_PRIVATE).apply {
                // 如果不为true侧点击没反应
                if(this?.getBoolean("user", false) != true) startActivity(Intent(context, LoginActivity::class.java))

                // 获取按钮文字状态，获取到的是：“退出登录” 的话侧点击事件是退出账号
                if(mBindIng.button.text == "退出登录") {

                    AlertDialog.Builder(context).apply {
                        setTitle("提示！")
                        setMessage("确定要退出登录吗?")

                        // 确定
                        setPositiveButton("确定"){ _, _ ->
                            activity?.getSharedPreferences("token", Context.MODE_PRIVATE)?.edit().apply {
                                this?.putBoolean("user", false)
                                // 把现有的token删除
                                this?.putString("token", "")
                                this?.apply()
                                activity?.runOnUiThread {
                                    onStart()
                                }
                            }
                        }

                        // 取消
                        setNegativeButton("取消"){ _, _ ->

                        }
                        show()
                    }


                }
            }

        }

    }


    /**
     * 设置列表数据
     */
    private fun initListItem() {
        // 设置RecyclerView适配器
        val layout = LinearLayoutManager(context)
        mBindIng.personRecyclerView.layoutManager = layout
        val adapter = PersonListItemRecyclerViewAdapter(array)
        mBindIng.personRecyclerView.adapter = adapter

        array.add(ListItemRecyclerViewEntity(R.drawable.base_1, "个人信息"))
        array.add(ListItemRecyclerViewEntity(R.drawable.base_2, "订单列表"))
        array.add(ListItemRecyclerViewEntity(R.drawable.base_3, "修改密码"))
        array.add(ListItemRecyclerViewEntity(R.drawable.base_4, "意见反馈"))
    }


    /**
     * 判断是否已经登录
     */
    override fun onStart() {
        super.onStart()

        code()
        context?.getSharedPreferences("token", Context.MODE_PRIVATE).apply {
            val token = this?.getString("token", "").toString()
            viewModel.setLogin(token)
            viewModel.loginDataLive.observe(this@PersonFragment, Observer { resources ->
                val body = resources.getOrNull()
                if (body != null){
                    mBindIng.personTvTitle.text = body.userName
                    mBindIng.button.text = "退出登录"
                }else {
                    mBindIng.personTvTitle.text = "你还未登录！"
                    mBindIng.button.text = "登录"
                }
            })
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun code(){
        GlobalScope.launch {
            context?.getSharedPreferences("token", Context.MODE_PRIVATE)?.apply {
                val token = this.getString("token", "").toString()
                val a = getLoginAll(token)
                if (a.code == 401){
                    activity?.getSharedPreferences("token", Context.MODE_PRIVATE)?.edit().apply {
                        this?.putBoolean("user", false)
                        this?.putString("token", "")
                        this?.apply()
                    }
                }
            }
        }


    }
}